<?php

/**
 * 淘宝商品获取
 *
 * @author andery
 */
class taobao_itemcollect {
    private $_code = 'taobao';
    public function fetch($url) {
        $id = $this->get_id($url);
        if (!$id) {
            return false;
        }
        $key = 'taobao_' . $id;
        $item_site = M('item_site')->where(array('code' => $this->_code))->find();
        //使用淘宝开放平台API
        vendor('Taobaotop.TopClient');
        vendor('Taobaotop.RequestCheckUtil');
        vendor('Taobaotop.Logger');
        $tb_top = new TopClient;
        $tb_top->appkey = $item_site['appkey'];
        $tb_top->secretKey = $item_site['secret'];
        $req = $tb_top->load_api('ItemGetRequest');
        $req->setFields('title,price,item_img,sell_point,num_iid');
        $req->setNumIid($id);
        $resp = $tb_top->execute($req);
        if (!isset($resp->item)) {
            return false;
        }
        $item = (array) $resp->item;
        return $item;
    }

    public function get_id($url) {
        $id = 0;
        $parse = parse_url($url);
        if (isset($parse['query'])) {
            parse_str($parse['query'], $params);
            if (isset($params['id'])) {
                $id = $params['id'];
            } elseif (isset($params['item_id'])) {
                $id = $params['item_id'];
            } elseif (isset($params['default_item_id'])) {
                $id = $params['default_item_id'];
            }
        }
        return $id;
    }

    public function get_key($url) {
        $id = $this->get_id($url);
        return 'taobao_' . $id;
    }

}